package com.starxg.m3u8.controller;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

import org.apache.commons.lang3.SystemUtils;

import com.starxg.m3u8.M3U8Application;
import com.starxg.m3u8.gui.DialogUtils;

import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Labeled;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.stage.Window;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * BaseController
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-05-17 01:04
 */
@SuppressWarnings("all")
@Setter
@Getter
@Slf4j
public class BaseController implements Initializable, InitializationWindow {

    private Window stage;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initView();
        initData();
        initEvent();
    }

    public void alert(String message) {
        DialogUtils.alert(message, getStage());
    }

    public void alert(String message, Alert.AlertType type) {
        DialogUtils.alert(message, type, getStage());
    }

    public boolean confirm(String message) {
        return DialogUtils.confirm(message, getStage());
    }

    public String prompt(String message, String defaultValue) {
        return DialogUtils.prompt(message, defaultValue, getStage());
    }

    public void openDocument(ActionEvent e) {
        String url = null;
        Object source = e.getSource();

        if (source instanceof Node) {
            url = ((Region) source).getUserData().toString();
        } else if (source instanceof MenuItem) {
            url = ((MenuItem) source).getUserData().toString();
        }

        if (url != null) {
            openDocument(url);
        }
    }

    public void openDocument(String url) {
        M3U8Application.getApplication().getHostServices().showDocument(url);
    }

    /**
     * 打开文件夹并选中文件
     */
    public void openFinderLightFile(File file) {
        String command;
        if (SystemUtils.IS_OS_MAC) {
            command = "open -R " + file.getAbsolutePath();
        } else if (SystemUtils.IS_OS_WINDOWS) {
            command = "explorer /select, " + file.getAbsolutePath();
        } else {
            return;
        }

        try {
            Runtime.getRuntime().exec(command).waitFor();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    protected static void disableComponents(Pane pane, boolean disable) {
        for (Node node : pane.getChildren()) {
            if (node instanceof TextInputControl || node instanceof Labeled) {
                node.setDisable(disable);

            }
            if (node instanceof Pane) {
                disableComponents((Pane) node, disable);
            }
        }
    }
}
